package com.test.study.reflect;

import org.junit.Before;
import org.junit.Test;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;

public class DemoReflect {
    Map<String, Object> map = new HashMap<>();
    @Before
    public void before(){

        map.put("username", "tom");
        map.put("age", 20);
        map.put("sex", "男");
        map.put("address", "北京");
    }
    @Test
    public void testField() throws Exception {

        Class<?> clazz = Class.forName("com.test.study.reflect.User");
        Object instance = clazz.newInstance();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            String name = field.getName();
            field.setAccessible(true);
            Object o = map.get(name);
            if(Objects.nonNull(o)){
                field.set(instance,o);
            }
        }
        System.out.println(instance);

    }

    @Test
    public void testMethod() throws  Exception{
        Class<?> clazz = Class.forName("com.test.study.reflect.User");
        Object instance = clazz.newInstance();
        Method[] declaredMethods = clazz.getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            declaredMethod.setAccessible(true);
            String name = declaredMethod.getName();
            if(name.startsWith("set")){
                String fieldName = name.substring(3).toLowerCase(Locale.ROOT);
                Object o = map.get(fieldName);
                if(Objects.nonNull(o)){
                    declaredMethod.invoke(instance,o);
                }
            }
        }
        System.out.println(instance);
    }
}
